﻿//
// Copyright (c) 2011 Western Data Solutions (www.westerndatasolutions.com) (Armen Shimoon)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without 
// limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 
// the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;

namespace WDS.Bencode
{
    /// <summary>
    /// Base class for all bencoded elements
    /// </summary>
    public abstract class BencodeElement : IComparable<BencodeElement>
    {
        /// <summary>
        /// Helper for determining whether the passed in bencoded element is a null object
        /// </summary>
        /// <typeparam name="T">The type of the passed in element (used to restrict to bencoded elements)</typeparam>
        /// <param name="item">The bencoded element</param>
        /// <returns>True if the bencoded element is a null object</returns>
        public bool IsNull<T>(T item) where T : BencodeElement
        {
            var itemType = item.GetType();

            if (typeof(NullBencodeDictionary).IsAssignableFrom(itemType))
            {
                return true;
            }

            if (typeof(NullBencodeInteger).IsAssignableFrom(itemType))
            {
                return true;
            }

            if (typeof(NullBencodeList).IsAssignableFrom(itemType))
            {
                return true;
            }

            if (typeof(NullBencodeString).IsAssignableFrom(itemType))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// Returns a null representation of the passed in bencoded element
        /// </summary>
        /// <typeparam name="T">The type of the element to get a null representation of</typeparam>
        /// <returns>The null object, ie <c>NullBencodeString</c></returns>
        public BencodeElement NullOf<T>() where T : BencodeElement
        {
            if (typeof(T).IsAssignableFrom(typeof(NullBencodeInteger)))
            {
                return new NullBencodeInteger();
            }
            else if (typeof(T).IsAssignableFrom(typeof(NullBencodeString)))
            {
                return new NullBencodeString();
            }
            else if (typeof(T).IsAssignableFrom(typeof(NullBencodeList)))
            {
                return new NullBencodeList();
            }
            else if (typeof(T).IsAssignableFrom(typeof(NullBencodeDictionary)))
            {
                return new NullBencodeDictionary();
            }
            return null;           
        }

        /// <summary>
        /// Helper for building a bencoded element from a string or integer
        /// </summary>
        /// <typeparam name="T">The type of the non-bencoded value</typeparam>
        /// <param name="value">The non bencoded value</param>
        /// <returns>A bencoded representation of the value (if it is an integer or string)</returns>
        protected BencodeElement BuildElementWithValue<T>(T value)
        {
            if (typeof(string).IsAssignableFrom(typeof(T)))
            {
                return Bencode.String(CastTo<string>(value));
            }
            else if (typeof(int).IsAssignableFrom(typeof(T)))
            {
                return Bencode.Integer(CastTo<int>(value));
            }
            else if (typeof(BencodeElement).IsAssignableFrom((typeof(T))))
            {
                return CastTo<BencodeElement>(value);
            }
    
            throw new Exception("Unrecognized type " + typeof(T).Name + " - should be string or int or bencode element.");

        }

        /// <summary>
        /// Helper for casting objects
        /// </summary>
        /// <typeparam name="T">Type to cast to</typeparam>
        /// <param name="value">Object to cast</param>
        /// <returns>Cased object</returns>
        protected T CastTo<T>(object value)
        {
            return (T) value;
        }

        /// <summary>
        /// Allows for semi-intelligent comparison of bencoded elements
        /// </summary>
        /// <param name="other">Element to compare to</param>
        /// <returns>0 if same</returns>
        public int CompareTo(BencodeElement other)
        {

            Type otherType = other.GetType();

            if (!this.GetType().IsAssignableFrom(otherType))
            {
                return 1;
            }
            if (typeof(BencodeDictionary).IsAssignableFrom(otherType))
            {
                return ((BencodeDictionary)this).CompareTo(((BencodeDictionary)other));
            }
            if (typeof(BencodeInteger).IsAssignableFrom(otherType))
            {
                return ((BencodeInteger)this).CompareTo(((BencodeString)other));
            }
            if (typeof(BencodeList).IsAssignableFrom(otherType))
            {
                return ((BencodeList)this).CompareTo(((BencodeList)other));
            }
            if (typeof(BencodeString).IsAssignableFrom(otherType))
            {
                return ((BencodeString) this).CompareTo(((BencodeString) other));
            }
            throw new Exception("Error while comparing couldn't cast type");
        }

        /// <summary>
        /// Tries to return the passed in value as the specified type, throwing an exception if not possible (and returning a null object if the argument is null)
        /// </summary>
        /// <typeparam name="T">The type to cast the passed in value to</typeparam>
        /// <param name="item">The bencoded value</param>
        /// <returns>A strongly typed bencoded value</returns>
        protected T TryReturnAs<T>(BencodeElement item) where T : BencodeElement
        {
            if (item == null)
            {
                return (T)NullOf<T>();
            }
            if (!typeof(T).IsAssignableFrom(item.GetType()))
            {
                throw new Exception("Expecting an item of type " + typeof(T).Name + " but found type " + item.GetType().Name + " instead.");
            }
            return (T)item;
        }

    }
}
